<template>
  <div class="modal">
    <div class="mask" @click="changeloginshow(false)"></div>
    <div class="loginBox">
      <div class="close">
        <img
          @click="changeloginshow(false)"
          src="@/assets/img/close.png"
          alt=""
        />
      </div>
      <section class="nav">
        <a
          href="#"
          :class="{ active: isShowContent }"
          @click.prevent="isShowContent = true"
          >手机号码登录</a
        >
        |
        <a
          href="#"
          :class="{ active: !isShowContent }"
          @click.prevent="showQrCode"
          >微信扫码登录</a
        >
      </section>
      <div class="content">
        <!-- 手机号码登录 -->
        <div class="phoneLogin" v-show="isShowContent">
          <div class="row">
            <input
              v-model.trim="phone"
              type="text"
              class="ipt"
              placeholder="请输入手机号"
            />
          </div>
          <div class="row">
            <!-- 滑动模块 -->
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              :slider-text="msg"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :imgs="codes"
              class="slide-box"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              class="ipt"
              placeholder="请输入短信验证码"
              v-model.trim="verifyCode"
            />
            <button
              class="btn btnCode"
              @click.prevent="getcode"
              v-show="count === 0"
            >
              获取验证码
            </button>
            <button class="btn btnCode" v-show="count !== 0">
              {{ count }}
            </button>
          </div>
          <div class="row">
            <button class="btn btnLogin" @click="login">登录</button>
          </div>
        </div>
        <!-- 微信二维码登录 -->
        <div class="qrLogin" id="weixin" v-show="!isShowContent"></div>
      </div>
    </div>
  </div>
</template>
<script>
import { valiphone } from "@/untis/index.js";
import { mapState, mapMutations, mapActions } from "vuex";
import {
  getmsgapi,
  getphoneReginapi,
  getPCLoginapi,
  getReginapi,
} from "@/request/api.js";
//插件图片引入
const imgs = [
  require("@/assets/img/integral-01.9386d4bf.png"),
  require("@/assets/img/integral-02.150d92a1.png"),
  require("@/assets/img/integral-02.150d92a1.png"),
  require("@/assets/img/integral-04.afadcbdf.png"),
];
export default {
  data() {
    return {
      isShowContent: true,
      msg: "向右滑动",
      codes: imgs,
      phone: "",
      verifyCode: "",
      count: 0,
      // uuid: "",
    };
  },
  computed: {},
  created() {
    this.invoke();
  },
  methods: {
    showQrCode() {
      // 展示二维码的div
      this.isShowContent = false;
      //获取二维码 并展示
      // 申请微信登录二维码
      let _this = this;
      // 这个new WxLogin 是微信那边提供的固定的api ， 从我们在 index.html 里面引入 script 那得到的
      new WxLogin({
        // id 就是你要显示二维码的对应的 元素的id
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死 ，是企业那边进行申请的，只能自己去 开发者平台，或者向后端要
        scope: "snsapi_login",
        // 扫码成功后重定向的接口 -- 也是后端给的
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          // 可以写成自己公司的域名或者location.origin,允许重定向http://127.0.0.1:8080
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLC5pbmZvIC5qc193eF9kZWZhdWx0X3RpcCwuaW5mbyAuanNfd3hfYWZ0ZXJfc2NhbiwuaW5mb3sNCiAgICBkaXNwbGF5OiBub25lOw0KfQ0K",
      });
    },
    ...mapMutations(["changeloginshow", "changetoastshow", "changeshopshow"]),
    ...mapActions(["asynctoasts"]),
    onSuccess() {
      //   let ms = (times / 1000).toFixed(1);
      this.msg = "验证成功";
    },
    // 拼图失败
    onFail() {
      this.msg = "验证失败"; // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "向右滑动";
    },
    login() {
      // 发请求注册
      // console.log(this.uuid);
      let uuid = sessionStorage.getItem("uuid");
      if (uuid) {
        getReginapi({
          verifyCode: this.verifyCode,
          phone: this.phone,
          uuid,
        }).then((res) => {
          if (res.code === 0) {
            // 购物车状态改变
            this.changeshopshow(true);
            localStorage.setItem("token", res["x-auth-token"]);
            this.changeloginshow(false);
            this.$emit("login");
            this.asynctoasts({
              toastmsg: "成功注册",
              toastIcon: "success",
            });
          }
        });
      } else {
        getphoneReginapi({
          verifyCode: this.verifyCode,
          phone: this.phone,
        }).then((res) => {
          if (res.code === 0) {
            // 发请求登录
            localStorage.setItem("token", res["x-auth-token"]);
            // 购物车状态改变
            this.changeshopshow(true);
            this.changeloginshow(false);
            this.$emit("login");
            this.asynctoasts({
              toastmsg: "成功登录",
              toastIcon: "success",
            });
          }
        });
      }
    },
    validate() {
      if (!valiphone(this.phone)) {
        // alert("手机号码不正确");
        this.asynctoasts({
          // 提示信息
          toastmsg: "请输入正确的手机号",
          toastIcon: "warning",
        });
        return false;
      }
      //   已经滑动验证码成功
      if (this.msg !== "验证成功") {
        this.asynctoasts({
          // 提示信息
          toastmsg: "请先进行滑动验证",
          toastIcon: "fail",
        });
        return false;
      }
      // 如果数据没问题，就返回true
      return true;
    },
    getcode() {
      // 获取验证码短信
      //确保手机是对的
      // var reg =
      //   /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (!this.validate()) {
        return;
      }
      // 手机号登录
      getmsgapi({ phone: this.phone }).then((res) => {
        if (res.code === 0) {
          console.log(res);
        } else {
        }
      });
      //   使用这个v-show显示和取消
      this.count = 60;
      const timer = setInterval(() => {
        this.count--;
        if (this.count == 0) {
          clearInterval(timer);
        }
      }, 1000);
    },
    invoke() {
      // code，调用
      let code = this.$route.query.code;
      if (code) {
        this.$router.push(this.$route.path);
        getPCLoginapi({ code }).then((res) => {
          console.log(res);
          if (res.code === 0) {
            // 直接扫码登录
            this.asynctoasts({
              toastmsg: "登录成功",
              toastIcon: "success",
            });
            localStorage.setItem("token", res["x-auth-token"]);
            // 更新vuex里面的 是否登录状态
            this.changeshopshow(true);
            this.$emit("login");
            // this.$route.query.code = "";
          } else if (res.code === 400) {
            // 注册
            this.asynctoasts({
              toastmsg: "等一会再登录",
              toastIcon: "error",
            });
          } else if (res.code === 407) {
            this.asynctoasts({
              toastmsg: "重新扫码注册",
              toastIcon: "error",
            });
            // console.log(res);
            this.uuid = res.uuid;
            // console.log(this.uuid);
            this.changeloginshow(true);
          }
        });
      }
    },
  },
  watch: {
    // 监听地址变化，进行判断
    "$route.path": function (newval, oldval) {
      console.log(newval, oldval);
      // 监听路由跳转，保证其他不同懒加载页面一样可以进行登录刷新获取code
      this.invoke();
    },
  },
};
</script>
<style lang="less" scoped>
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .loginBox {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    .close {
      position: absolute;
      right: 60px;
      top: 16px;
      height: 22px;
      width: 22px;
      background: url("../assets/img/close.png");
    }
    .nav {
      display: flex;
      justify-content: center;
      font-size: 20px;
      padding-top: 50px;
      a {
        padding: 0 10px;
        color: #999;
        text-decoration: none;
        &.active {
          color: #333;
        }
      }
    }
    .content {
      width: 355px;
      margin: 20px auto 0;
      height: 200px;
      #weixin {
        // background-color: red;
        display: flex;
        justify-content: center;
        margin-top: -20px;
      }
      .phoneLogin {
        .row {
          display: flex;
          margin-bottom: 20px;
        }
        .ipt {
          box-shadow: 0;
          flex: 1;
          height: 48px;
        }
        .btn {
          color: #fff;
          background-color: #0a328e;
          border: none;
          cursor: pointer;
        }
        .btnCode {
          margin-left: 10px;
          line-height: 50px;
          width: 100px;
          text-align: center;
        }
        .btnLogin {
          width: 100%;
          height: 50px;
          line-height: 50px;
        }
      }
    }
  }
}
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>